package geektime.spring.springbucks.service.impl;

import geektime.spring.springbucks.exception.RollbackException;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.service.CoffeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CoffeeServiceImpl implements CoffeeService {
    @Autowired
    private CoffeeMapper coffeeMapper;

    //新增
    @Transactional
    public int saveCoffee(Coffee coffee){
        return coffeeMapper.save(coffee);
    }

    //查询
    public Coffee queryById(Long id){
        return coffeeMapper.findById(id);
    }

    //批量查询
    public List<Coffee> queryByIdList(List<Long> ids){
        return  coffeeMapper.findListById(ids);
    }

    //分页查询
    public List<Coffee> findAllWithRowBounds(RowBounds rowBounds){
        return coffeeMapper.findAllWithRowBounds(rowBounds);
    }
    public List<Coffee> findAllWithParam(int pageNum, int pageSize){
        return coffeeMapper.findAllWithParam(pageNum, pageSize);
    }

    //改
    @Transactional
    public int updateById(Coffee cofee){
        return coffeeMapper.updateByPrimaryKey(cofee);
    }
    @Transactional(rollbackFor = RollbackException.class)
    public void updateById2(Coffee cofee) throws RollbackException {
        coffeeMapper.updateByPrimaryKey(cofee);
        throw new RollbackException();
    }
    @Transactional
    public void updateById3(Coffee cofee) {
        coffeeMapper.updateByPrimaryKey(cofee);
        try {
            Thread.sleep(200);
        }catch (Exception e){

        }
    }

    //删
    @Transactional
    public int deleteById(Long id){
        return coffeeMapper.deleteByPrimaryKey(id);
    }


}
